package AttachmentService

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"seawolf-admin-go/internal/request/AttachmentReq"
	"seawolf-admin-go/utility/response"
	"strings"
)

func UploadChunk(r *ghttp.Request) *response.JsonResponse {
	var parames *AttachmentReq.UploadChunk
	var err error
	ctx := r.GetCtx()
	g.TryCatch(ctx, func(ctx context.Context) {
		err = r.Parse(&parames)
	}, func(ctx context.Context, exception error) {
		if strings.Contains(exception.Error(), "EOF") {
			fmt.Println("UploadChunk 文件断流 错误本体：", exception.Error())
		}
		err = exception
	})
	if err != nil {
		return response.FailByRequestMessage(r, "上传失败："+err.Error())
	}
	//设置内存大小
	err = r.ParseMultipartForm(32 << 20) // 双目运算 32*2^20
	if err != nil {
		return response.FailByRequestMessage(r, "上传失败："+err.Error())
	}
	file := r.GetUploadFile("file")
	if file == nil {
		return response.FailByRequestMessage(r, "文件不能为空")
	}
	aModel, err := GetModelByMd5(ctx, parames.FileMd5)
	if err != nil {
		return response.FailByRequestMessage(r, "上传失败："+err.Error())
	}
	if aModel != nil {
		return response.JsonByAll(r, 21001, "文件已存在")
	}
	var oneByte int64 = 1048576 // 1MB
	// 默认允许上传5MB
	allowSizeConfigTmp, _ := g.Cfg().Get(ctx, "upload.AllowSize", 5)
	allowSizeConfig := allowSizeConfigTmp.Int64()
	allowSize := allowSizeConfig * oneByte
	if file.Size > allowSize {
		return response.FailByRequestMessage(r, "文件大小不能超过"+gconv.String(allowSizeConfig)+"MB")
	}
	uploadChunkPathTmp, _ := g.Cfg().Get(ctx, "upload.UploadChunkPath", "")
	uploadChunkPath := uploadChunkPathTmp.String()

	_, err = pieceSave(ctx, uploadChunkPath, parames.PieceMd5, file)
	if err != nil {
		return response.FailByRequestMessage(r, "上传失败："+err.Error())
	}
	// 保存分片信息
	err = chunkAdd(ctx, parames.Index, parames.FileMd5, parames.PieceMd5)
	if err != nil {
		return response.FailByRequestMessage(r, "上传失败："+err.Error())
	}
	// 判断是否上传完成
	isFinish, err := chunkIsFull(ctx, parames.FileMd5, parames.Chunks)
	if err != nil {
		return response.FailByRequestMessage(r, "上传失败："+err.Error())
	}
	if !isFinish {
		return response.SuccessByRequestMessageData(r, "分片上传完成", parames.Index)
	}
	return response.JsonByAll(r, 21004, "全部上传完成")
}
